import javax.naming.*
import javax.jms.*

/** Obtain a connection factory from JNDI and create a JMS session, then pass
    to user closure. */
def withJmsSession(closure) {
	def ctx = new InitialContext()
	try {
		def cf = ctx.lookup("ConnectionFactory") as ConnectionFactory
		def conn = cf.createConnection()
		try {
			def session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE)
			conn.start()
			closure.call(session)
			session.close()
		} finally {
			conn.close()
		}
	} finally {
		ctx.close()
	}
}
//withJmsSession { session -> println(session) }
def sendMsgToQueue(session, msg, queueName) {
	println("Sending JMS msg to queue ${queueName}")
	def queue = session.createQueue(queueName)
	def producer = session.createProducer(queue)
	producer.send(msg)
}
def sendTextFileToQueue(session, textFile, queueName) {
	def textMsg = session.createTextMessage(textFile.text)
	textMsg.setStringProperty("filePath", textFile.path)
	sendMsgToQueue(session, textMsg, queueName)
	println("File sent: ${textFile}")
}


/** Setup a timer that run a closure as task. Also register the timer to be shutdown
    in JMV shutdown hook. */
class ClosureTimerTask extends TimerTask {
	def Closure closure
	def ClosureTimerTask(closure) { this.closure = closure }
	def void run() { closure.call() }
}
def setupTimerTask(period, closure) {
	def timer = new Timer()
	timer.scheduleAtFixedRate(new ClosureTimerTask(closure), 1000, period)
	Runtime.getRuntime().addShutdownHook(new Thread({ 
		println("Shutting timer " + timer)
		timer.cancel() 
	} as Runnable))
}

// Poll a directory for file and sends the content to a Queue
// fileToQueue.groovy <dirName> <queueName>
// groovy.bat fileToQueue.groovy "D:\apps\cygwin\tmp\fileToQueue" ExampleQueue
def dirName = args[0]
def queueName = args[1]

def dir = new File(dirName)
def archiveDir = new File(dir, ".archive")
archiveDir.mkdirs()

println("Scanning ${dir} every 3 secs.")
setupTimerTask(3000) {
	def files = dir.listFiles()
  if (files != null) {
		files.toList().findAll { f -> f.name != ".archive" }.each { file ->
			println("File ${file} found.")
			withJmsSession { session -> sendTextFileToQueue(session, file, queueName) }
			def archiveFile = new File(archiveDir, file.name)
			def count = 0
			while (archiveFile.exists()) 
				archiveFile = new File(archiveDir, file.name + "." + (++count))
			file.renameTo(archiveFile)
		}
	}
}